package com.ecnu.codelearn.thread.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 曹培胜
 * @Date: 2021/09/14/16:27
 * @Description:
 */
public class Demo1 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        AtomicInteger atomicInteger = new AtomicInteger();

        // 发起请求,runAsync没有返回值的异步回调
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
        });


        //supplyAsync有返回结果的异步回调
        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(()-> {
            System.out.println("completableFuture2");
            int i = 10/0;
            return 12;
        });
        // System.out.println(completableFuture2.get());//获取completableFuture2的值，会阻塞
        // System.out.println(completableFuture.get());//获取completableFuture的值，会阻塞

        System.out.println(completableFuture2.whenComplete((t, u) -> {
            System.out.println("t=>" + t);// 正常的返回结果
            System.out.println("u=>" + u);// 错误信息 java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
        }).exceptionally(throwable -> { // 处理异常
            System.out.println(throwable.getMessage());
            return 500;
        }).get());

        Thread.sleep(10000);
    }
}
